package com.wushi.dynamiccompile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

import com.sun.org.apache.bcel.internal.generic.LoadClass;

public class MyCompiler {

	private static final String CLASS_PATH = "/Users/heitu";

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		StandardJavaFileManager standardFileManager = compiler.getStandardFileManager(null, null, null);
		String files="/Users/heitu/DynamicTest.java";
		Iterable<? extends JavaFileObject> fileObjects = standardFileManager.getJavaFileObjects(files);
		//设置编译参数
		ArrayList<String> ops = new ArrayList<String>();
		ops.add("-Xlint:unchecked");
		//设置classpath
		ops.add("-classpath");
		ops.add(CLASS_PATH);
		
		
		CompilationTask task = compiler.getTask(null, standardFileManager, null, null, null, fileObjects);
		task.call();
		System.out.println("compile success..."+ files);
		try {
			Thread.currentThread().sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			
			//动态加载生成的class文件到内存
			DynamicClassLoader loader=new DynamicClassLoader();
			Class<?> class1 = loader.findClass("/Users/heitu/DynamicTest.class");
			System.out.println("loading class..."+class1.getName());
			//获取此类的方法
			Method method = class1.getDeclaredMethod("showme", String.class);
			//执行方法，注意第一个参数为class的示例
			Object result = method.invoke(class1.newInstance(),"zhangsan");
			System.out.println("the result:"+result);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
	

}
